package com.bfsuol.bfsuolframework.core.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.bfsuol.bfsuolcomponents.file.dao.FileManager;
import com.bfsuol.bfsuolframework.core.controller.json.MessageJson;
import com.bfsuol.bfsuolframework.core.controller.support.Pagination;
import com.bfsuol.bfsuolframework.core.controller.support.QueryParam;
import com.bfsuol.bfsuolframework.core.entity.Entity;
import com.bfsuol.bfsuolframework.core.spring.QueryParameter;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

public abstract class CRUDControllerSupportV2<E extends Entity> extends SpringControllerSupport implements SpringController {

	public abstract IService<E> getService();
	
	@RequestMapping("/index")
	public ModelAndView index(Model model){
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName(getViewNamedPath("index"));
		return modelAndView;
	}
	
	@RequestMapping("/list")
	public ModelAndView list(
			@QueryParameter("query") QueryParam query,
			@ModelAttribute("page") Pagination page){

		Pagination pagination = new Pagination();
		pagination.setItems(getService().list());
		pagination.setTotalRecord(10);
		pagination.setCurrentPage(1);

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName(getViewNamedPath("list"));
		return modelAndView;
	}

	@RequestMapping("/input")
	public ModelAndView create(@ModelAttribute E entity,Model model){

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName(getViewNamedPath("input"));
		return modelAndView;
	}
	
	@RequestMapping("/input/{id}")
	public ModelAndView edit(@PathVariable("id") Long id, Model model){
		E entity = getService().getById(id);
		model.addAttribute(entity);

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName(getViewNamedPath("input"));
		return modelAndView;
	}
	
	@RequestMapping("/save")
	public @ResponseBody MessageJson save(@ModelAttribute E entity){
		if(entity.isNew()){
			getService().save(entity);
		}else{
			getService().updateById(entity);
		}
		return MessageJson.information("保存成功");
	}
	
	
	@RequestMapping("/delete/{id}")
	public @ResponseBody MessageJson delete(@PathVariable("id") Long id){
		getService().removeById(id);
		return MessageJson.information("成功删除1条");
	}
	
	@RequestMapping("/delete")
	public @ResponseBody MessageJson delete(@RequestParam("ids") Long[] ids){
		if(ids == null || ids.length == 0){
			return MessageJson.error("没有删除");
		}
		for(Long id : ids){
			getService().removeById(id);
		}
		return MessageJson.information("成功删除"+ids.length+"条");
	}
}
